package sg.edu.nus.comp.icreate.ivletalk.forum;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ForumThread implements Comparable<ForumThread> {
	private ForumThread parent;
	private List<ForumThread> replies = new ArrayList<ForumThread>();
	private String id;
	private int numReplies;
	private String title;
	private String body;
	private Calendar date;
	private String poster;
	private int totalCount = 0;

	public ForumThread(ForumThread parent) {
		this.parent = parent;
	}

	public ForumThread() {

	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getNumReplies() {
		return numReplies;
	}

	public void setNumReplies(int numReplies) {
		this.numReplies = numReplies;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public Calendar getDate() {
		return date;
	}

	public void setDate(Calendar date) {
		this.date = date;
	}

	public String getPoster() {
		return poster;
	}

	public void setPoster(String poster) {
		this.poster = poster;
	}

	public ForumThread getParent() {
		return parent;
	}

	public void setParent(ForumThread parent) {
		this.parent = parent;
	}

	public List<ForumThread> getReplies() {
		return replies;
	}

	public int getCount() {
		if (totalCount == 0) {
			totalCount = 1;
			for (ForumThread r : replies)
				totalCount += r.getCount();
		}
		return totalCount;
	}

	public ForumThread getTheadbyPosition(int position) {
		int traversed = 1;
		if (position == 0)
			return this;
		for (ForumThread r : replies) {
			if (position - traversed < r.getCount())
				return r.getTheadbyPosition(position - traversed);
			else
				traversed += r.getCount();
		}
		return null;
	}

	public String toString() {
		return title + " " + poster + "  " + getDisplayTime();
	}

	private String getDisplayTime() {
		StringBuilder builder = new StringBuilder();
		// Date
		builder.append(date.get(Calendar.DATE)).append("/").append(date.get(Calendar.MONTH)).append("/").append(date.get(Calendar.YEAR));
		builder.append(" ");
		// Hour
		String hr = date.get(Calendar.HOUR) > 10 ? "" : "0";
		hr += date.get(Calendar.HOUR);
		builder.append(hr).append(":");
		// Minute
		String min = date.get(Calendar.MINUTE) > 10 ? "" : "0";
		min += date.get(Calendar.MINUTE);
		builder.append(min).append(" ").append(date.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM");
		return builder.toString();
	}

	@Override
	public int compareTo(ForumThread another) {
		return (-1) * this.date.compareTo(another.date);
	}

}
